//
//  BBMeViewController.swift
//  BBLinkiOSProject
//
//  Created by liuzhu on 2018/11/29.
//  Copyright © 2018 liuzhu. All rights reserved.
//

import AFNetworking
import SDWebImage
import SVProgressHUD
import UIKit
class BBMeViewController: UIViewController {
    @IBOutlet var headImage: UIImageView!
    @IBOutlet var nameLabel: UILabel!

    @IBOutlet var myDefaultDeviceImage: UIImageView!
    @IBOutlet var myDevaultDeviceName: UILabel!
    @IBOutlet var distanceLabel: UILabel!
    @IBOutlet var activationTimeLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Me"
        if !BBUser.userLogin() {
            navigationItem.rightBarButtonItem?.isEnabled = false
            navigationItem.rightBarButtonItem?.title = ""
        }
        showUser()
        headImageUI()
    }

    @IBAction func close(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }

    @IBAction func logout(_ sender: Any) {
        let con = UIAlertController(title: "Alert", message: "Are you sure you want to log out?", preferredStyle: UIAlertController.Style.alert)
        let okAc = UIAlertAction(title: "Sure", style: UIAlertAction.Style.default) { _ in
            BBUser.removeUser()
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: BBSwitchRootViewControllerKey), object: false)
        }
        let cancelAc = UIAlertAction(title: "cancel", style: UIAlertAction.Style.cancel) { _ in
        }
        con.addAction(okAc)
        con.addAction(cancelAc)
        present(con, animated: true, completion: nil)
    }

    @IBAction func refreshDistanceAction(_ sender: Any) {
        SVProgressHUD.show()
        let path = "device/info.do"
        let params = ["token": BBUser.loadUser()?.token, "userId": BBUser.loadUser()?.userId, "deviceId": BBUser.loadUser()?.devices?.first?.deviceId]
        AFNetWorkManager.shareNetworkTools().post(path, parameters: params, progress: nil, success: { _, json in
            let dict = json as! [String: AnyObject]
            let dictStatus = dict["status"] as! NSNumber
            if dictStatus.intValue == 0 {
                let deviceDic = dict["data"] as! [String: AnyObject]
                let device = BBDevice(dict: deviceDic)
                var devices = BBUser.loadUser()?.devices
                if devices?.count != 0 {
                    for i in 1 ... devices!.count {
                        let dev = devices![i - 1]
                        if dev.deviceId == device.deviceId {
                            devices?.remove(at: i - 1)
                            devices?.append(device)
                        }
                    }
                }
                BBUser.loadUser()?.resetDevices(devices: devices!)
                self.showUser()
            }
            SVProgressHUD.dismiss()
        }) { _, _ in
            SVProgressHUD.dismiss()
        }
    }

    private func showUser() {
        let user = BBUser.loadUser()
        nameLabel.text = user?.userName
        let strHead = user?.headImage
        let url = URL(string: strHead ?? " ")
        headImage?.sd_setImage(with: url, placeholderImage: UIImage(named: "default_head"), options: SDWebImageOptions(rawValue: 1), completed: nil)
        let deviceImage = user?.devices?.first?.deviceImages
        let deviceUrl = URL(string: deviceImage ?? " ")
        myDefaultDeviceImage?.sd_setImage(with: deviceUrl, placeholderImage: UIImage(named: "default_head"), options: SDWebImageOptions(rawValue: 1), completed: nil)
        myDevaultDeviceName.text = user?.devices?.first?.deviceName
        activationTimeLabel.text = BBUtils.timeStampToString(timeStamp: user?.devices?.first?.updateTime as! Int)
        let distanceK = Int(truncating: (user?.devices?.first?.mileage ?? 0)) / 1000
        let distanceM = (Int(truncating: (user?.devices?.first?.mileage ?? 0)) % 1000) / 100
        distanceLabel.text = "\(distanceK).\(distanceM)km"
    }

    private func headImageUI() {
        headImage.layer.cornerRadius = 45
        headImage.layer.masksToBounds = true
    }

    @IBAction func changeHead(_ sender: Any) {
        present(selectorController, animated: true, completion: nil)
    }

    // MARK: 用于弹出选择的对话框界面
    var selectorController: UIAlertController {
        let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        controller.addAction(UIAlertAction(title: "cancel", style: .cancel, handler: nil)) // 取消按钮
        controller.addAction(UIAlertAction(title: "拍照选择", style: .default) { _ in
            self.selectorSourceType(type: .camera)
        }) // 拍照选择
        controller.addAction(UIAlertAction(title: "相册选择", style: .default) { _ in
            self.selectorSourceType(type: .photoLibrary)
        }) // 相册选择
        return controller
    }

    func selectorSourceType(type: UIImagePickerController.SourceType) {
        let vc = UIImagePickerController()
        vc.delegate = self
        vc.sourceType = type
        // 打开图片选择器
        present(vc, animated: true, completion: nil)
    }

    private func reLoadUser() {
        SVProgressHUD.show()
        let path = "user/get_user_info.do"
        let params = ["token": BBUser.loadUser()?.token, "account": BBUser.loadUser()?.email]
        AFNetWorkManager.shareNetworkTools().post(path, parameters: params, progress: nil, success: { _, json in
            let dict = json as! [String: AnyObject]
            let userdic = dict["data"] as! [String: AnyObject]
            var user = BBUser.loadUser()
            user?.resetUserData(dict: userdic)
            self.showUser()
            SVProgressHUD.dismiss()
        }) { _, _ in
            SVProgressHUD.dismiss()
        }
    }
}

extension BBMeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    // MARK: 图片选择器界面
    var imagePickerController: UIImagePickerController {
        let imagePicket = UIImagePickerController()
        imagePicket.delegate = self
        imagePicket.sourceType = .photoLibrary
        return imagePicket
    }

    // MARK: 当图片选择器选择了一张图片之后回调
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
        dismiss(animated: true, completion: nil) // 选中图片, 关闭选择器...这里你也可以 picker.dismissViewControllerAnimated 这样调用...但是效果都是一样的...
        SVProgressHUD.show()
        headImage.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage // 显示图片
        headImage.contentMode = .scaleToFill // 缩放显示, 便于查看全部的图片
        let path = "user/upload.do"
        let params = ["token": BBUser.loadUser()?.token, "userId": BBUser.loadUser()?.userId]
        BBUploadImage.shareBBUploadImage().upload(path: path, params: params as! [String: AnyObject], image: headImage.image!, maxSizeByte: 100 * 1024) { isSuccess in
            let result = isSuccess
            if result {
                self.reLoadUser()
            } else {
                SVProgressHUD.dismiss()
                SVProgressHUD.showInfo(withStatus: "failed")
            }
        }
    }

    // MARK: 当点击图片选择器中的取消按钮时回调
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil) // 效果一样的...
    }
}
